/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AfterUbuntu.java
 *
 * Created on 14-feb-2011, 20:46:26
 */

package afterubuntu.view;

import afterubuntu.log.Log;
import afterubuntu.pojo.APTPackage;
import afterubuntu.pojo.AfterUbuntuData;
import afterubuntu.pojo.Application;
import afterubuntu.pojo.AutConfiguration;
import afterubuntu.pojo.Category;
import afterubuntu.pojo.CmdConfiguration;
import afterubuntu.pojo.DEBPackage;
import afterubuntu.pojo.GPARepository;
import afterubuntu.pojo.GetConfiguration;
import afterubuntu.pojo.IcoConfiguration;
import afterubuntu.pojo.PPARepository;
import afterubuntu.pojo.REMPackage;
import afterubuntu.pojo.RepositoryKey;
import afterubuntu.pojo.ZipConfiguration;
import afterubuntu.script.ExecuteScript;
import afterubuntu.script.GenerateScript;
import afterubuntu.script.GenerateScriptListener;
import afterubuntu.util.AlphabeticalSort;
import java.awt.GraphicsEnvironment;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Vector;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultCaret;


/**
 *
 * @author Kermit
 */
public class AfterUbuntu extends javax.swing.JFrame implements GenerateScriptListener{

    String categorySelected;
    AfterUbuntuData afterUbuntuData;
    private int lastIndex = -1;
    private ProvideFeedback provideFeedback;
    private GenerateScript generateScript;

    ExecuteScript ejecuteScript;

    /** Creates new form AfterUbuntu */
    public AfterUbuntu() {
        initComponents();
        checkBoxList = new CheckBoxList();
        checkBoxList.addMouseListener(new MouseAdapter(){
            @Override
            public void mousePressed(MouseEvent e){
                int index = checkBoxList.locationToIndex(e.getPoint());
                if (index != -1) {
                    JCheckBox checkbox = (JCheckBox) checkBoxList.getModel().getElementAt(index);
                    Application application = afterUbuntuData.getCategory(categorySelected).getApplication(checkbox.getText());
                    if(index == lastIndex){
                        checkbox.setSelected(!checkbox.isSelected());
                        repaint();
                        application.setInstall(checkbox.isSelected());
                    }else{
                        lastIndex = index;
                        updateTasks(application);
                    }
                }
            }
        });
        applications.setViewportView(checkBoxList);
        afterUbuntuData = null;
        categorySelected = null;
        generating.setVisible(false);
        this.setSize(this.getWidth(), 275);
        generate.requestFocusInWindow();
        DefaultCaret caret = (DefaultCaret) console.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    }

    public void setAfterUbuntuData(AfterUbuntuData afterUbuntuData) {
        this.afterUbuntuData = afterUbuntuData;
    }

    public void loadAfterUbuntuCategories(){

        Vector<String> categoriesListV = new Vector<String>();
        HashMap<String, Category> categoriesHM = afterUbuntuData.getCategories();

        for(String categoryName : categoriesHM.keySet()){
            categoriesListV.add(categoryName);
            Category category = categoriesHM.get(categoryName);
            
        }

        Collections.sort(categoriesListV, new AlphabeticalSort());
        categoriesList.setListData(categoriesListV);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        categories = new javax.swing.JScrollPane();
        categoriesList = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        applications = new javax.swing.JScrollPane();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tasks = new javax.swing.JTextArea();
        exit = new javax.swing.JButton();
        generate = new javax.swing.JButton();
        checkAll = new javax.swing.JCheckBox();
        uncheckAll = new javax.swing.JCheckBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        console = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        generating = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("AfterUbuntu");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Categories"));

        categoriesList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                categoriesListMouseClicked(evt);
            }
        });
        categories.setViewportView(categoriesList);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(categories, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(categories, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Applications"));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(applications, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(applications, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Tasks"));

        tasks.setColumns(20);
        tasks.setEditable(false);
        tasks.setRows(5);
        jScrollPane1.setViewportView(tasks);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 704, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                .addContainerGap())
        );

        exit.setText("Exit");
        exit.setNextFocusableComponent(generate);
        exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitActionPerformed(evt);
            }
        });

        generate.setText("Generate script");
        generate.setNextFocusableComponent(exit);
        generate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generateActionPerformed(evt);
            }
        });

        checkAll.setSelected(true);
        checkAll.setText("check all");
        checkAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkAllActionPerformed(evt);
            }
        });

        uncheckAll.setText("uncheck all");
        uncheckAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uncheckAllActionPerformed(evt);
            }
        });

        console.setBackground(new java.awt.Color(0, 0, 0));
        console.setColumns(20);
        console.setEditable(false);
        console.setForeground(new java.awt.Color(255, 255, 255));
        console.setRows(5);
        console.setDoubleBuffered(true);
        jScrollPane2.setViewportView(console);

        jLabel1.setText("Console:");

        generating.setText("Generating script.  ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(238, 238, 238)
                        .addComponent(checkAll)
                        .addGap(18, 18, 18)
                        .addComponent(uncheckAll)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 351, Short.MAX_VALUE)
                        .addComponent(generating)
                        .addGap(36, 36, 36)
                        .addComponent(generate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exit, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(120, 120, 120)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(175, 175, 175)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(generate, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                        .addComponent(generating))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(checkAll)
                            .addComponent(uncheckAll))
                        .addComponent(exit, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)))
                .addGap(9, 9, 9)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void categoriesListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_categoriesListMouseClicked
        Vector<String> applicationNames = new Vector<String>();
        categorySelected = (String)categoriesList.getSelectedValue();
        Category category = afterUbuntuData.getCategory(categorySelected);
        HashMap<String, Application> applicationsHM = category.getApplications();
        for(Application application : applicationsHM.values()){
            applicationNames.add(application.getDescription());
        }
        Collections.sort(applicationNames, new AlphabeticalSort());
        checkBoxList.removeAll();
        tasks.setText("");
        for(int i = 0; i<applicationNames.size(); i++){
            checkBoxList.addCheckbox(new JCheckBox(applicationNames.elementAt(i), applicationsHM.get(applicationNames.elementAt(i)).getInstall()));
        }
        lastIndex = -1;
    }//GEN-LAST:event_categoriesListMouseClicked

    private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
        ejecuteScript.stop();
        System.exit(0);
    }//GEN-LAST:event_exitActionPerformed

    private void checkAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkAllActionPerformed
        checkAll.setSelected(true);

        if(categorySelected != null){
            Vector<String> applicationNames = new Vector<String>();
            Category category = afterUbuntuData.getCategory(categorySelected);
            HashMap<String, Application> applicationsHM = category.getApplications();
            for(Application application : applicationsHM.values()){
                application.setInstall(true);
                applicationNames.add(application.getDescription());
            }
            Collections.sort(applicationNames, new AlphabeticalSort());
            checkBoxList.removeAll();
            for(int i = 0; i<applicationNames.size(); i++){
                checkBoxList.addCheckbox(new JCheckBox(applicationNames.elementAt(i), applicationsHM.get(applicationNames.elementAt(i)).getInstall()));
            }
        }
    }//GEN-LAST:event_checkAllActionPerformed

    private void uncheckAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uncheckAllActionPerformed
        uncheckAll.setSelected(false);

        if(categorySelected != null){
            Vector<String> applicationNames = new Vector<String>();
            Category category = afterUbuntuData.getCategory(categorySelected);
            HashMap<String, Application> applicationsHM = category.getApplications();
            for(Application application : applicationsHM.values()){
                application.setInstall(false);
                applicationNames.add(application.getDescription());
            }
            Collections.sort(applicationNames, new AlphabeticalSort());
            checkBoxList.removeAll();
            for(int i = 0; i<applicationNames.size(); i++){
                checkBoxList.addCheckbox(new JCheckBox(applicationNames.elementAt(i), applicationsHM.get(applicationNames.elementAt(i)).getInstall()));
            }
        }
    }//GEN-LAST:event_uncheckAllActionPerformed

    private void generateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateActionPerformed
        generate.setEnabled(false);
        provideFeedback = new ProvideFeedback();
        Thread th = new Thread(provideFeedback);
        generating.setText("Generating script.  ");
        th.start();
        generateScript = new GenerateScript(afterUbuntuData);
        generateScript.addGenerateScriptListener(this);
        Thread th2 = new Thread(generateScript);
        th2.start();
    }//GEN-LAST:event_generateActionPerformed

    public void updateTasks(Application application){
        String text = "";

        text += "Description:\n";
        text += application.getDescription() + "\n\n";

        ArrayList<GPARepository> gpaRepositories = application.getGPARepositories();
        if(!gpaRepositories.isEmpty()){
            text += "Repositories to install:\n";
            for(GPARepository gpaRepository : gpaRepositories){
                text += gpaRepository.getName() + ": " + gpaRepository.getRepository() + "\n";
            }
            text += "\n\n";
        }       

        ArrayList<PPARepository> ppaRepositories = application.getPPARepositories();
        if(!ppaRepositories.isEmpty()){
            text += "PPA repositories to install:\n";
            for(PPARepository ppaRepository : ppaRepositories){
                text += ppaRepository.getName() + ": " + ppaRepository.getRepository() + "\n";
            }
            text += "\n\n";
        }

        ArrayList<RepositoryKey> repositoryKeys = application.getRepositoryKeys();
        if(!repositoryKeys.isEmpty()){
            text += "Keys to install:\n";
            for(RepositoryKey repositoryKey : repositoryKeys){
                text += repositoryKey.getKey() + "\n";
            }
            text += "\n\n";
        }

        ArrayList<APTPackage> aptPackages = application.getAPTPackages();
        if(!aptPackages.isEmpty()){
            text += "Packages to intall:\n";
            for(APTPackage aptPackage : aptPackages){
                ArrayList<String> apts = aptPackage.getAPTPackages();
                for(String apt : apts){
                    text += apt + " ";
                }
            }
            text += "\n\n";
        }

        ArrayList<DEBPackage> debPackages = application.getDEBPackages();
        if(!debPackages.isEmpty()){
            text += "Packages (deb) to intall:\n";
            for(DEBPackage debPackage : debPackages){
                ArrayList<String> debs = debPackage.getDEBPackages();
                for(String deb : debs){
                    text += deb + " ";
                }
            }
            text += "\n\n";
        }

        ArrayList<REMPackage> remPackages = application.getREMPackages();
        if(!remPackages.isEmpty()){
            text += "Packages to remove:\n";
            for(REMPackage remPackage : remPackages){
                ArrayList<String> rems = remPackage.getREMPackages();
                for(String rem : rems){
                    text += rem + " ";
                }
            }
            text += "\n\n";
        }

        ArrayList<ZipConfiguration> zipConfigurations = application.getZipConfigurations();
        ArrayList<CmdConfiguration> cmdConfigurations = application.getCmdConfigurations();
        ArrayList<GetConfiguration> getConfigurations = application.getGetConfigurations();
        ArrayList<IcoConfiguration> icoConfigurations = application.getIcoConfigurations();
        ArrayList<AutConfiguration> autConfigurations = application.getAutConfigurations();
        if(!zipConfigurations.isEmpty() || !cmdConfigurations.isEmpty() || !getConfigurations.isEmpty() || !icoConfigurations.isEmpty() || !autConfigurations.isEmpty()){
            text += "Software configuration actions:\n";
            for(ZipConfiguration zipConfiguration : zipConfigurations){
                text += "- Download " + zipConfiguration.getZipFile() + " and unzip to " + zipConfiguration.getDirectory() + "\n";
            }
            for(CmdConfiguration cmdConfiguration : cmdConfigurations){
                text += "- Execute " + cmdConfiguration.getCommand() + "\n";
            }
            for(GetConfiguration getConfiguration : getConfigurations){
                text += "- Download " + getConfiguration.getUrl() + " to " + getConfiguration.getDirectory() + "\n";
            }
            for(IcoConfiguration icoConfiguration : icoConfigurations){
                text += "- Download icon " + icoConfiguration.getUrl() + "\n";
            }
            for(AutConfiguration autConfiguration : autConfigurations){
                text += "- Download autoexecute launcher " + autConfiguration.getUrl() + "\n";
            }
            text += "\n\n";
        }

        ArrayList<ZipConfiguration> zipUsers = application.getZipUser();
        ArrayList<CmdConfiguration> cmdUsers = application.getCmdUser();
        ArrayList<GetConfiguration> getUsers = application.getGetUser();
        ArrayList<IcoConfiguration> icoUsers = application.getIcoUser();
        ArrayList<AutConfiguration> autUsers = application.getAutUser();
        if(!zipUsers.isEmpty() || !cmdUsers.isEmpty() || !getUsers.isEmpty() || !icoUsers.isEmpty() || !autUsers.isEmpty()){
            text += "User configuration actions:\n";
            for(ZipConfiguration zipUser : zipUsers){
                text += "- Download " + zipUser.getZipFile() + " and unzip to " + zipUser.getDirectory() + "\n";
            }
            for(CmdConfiguration cmdUser : cmdUsers){
                text += "- Execute " + cmdUser.getCommand() + "\n";
            }
            for(GetConfiguration getUser : getUsers){
                text += "- Download " + getUser.getUrl() + " to " + getUser.getDirectory() + "\n";
            }
            for(IcoConfiguration icoUser : icoUsers){
                text += "- Download icon " + icoUser.getUrl() + "\n";
            }
            for(AutConfiguration autUser : autUsers){
                text += "- Download autoexecute launcher " + autUser.getUrl() + "\n";
            }
            text += "\n\n";
        }

        String comment = application.getComment();
        if(comment != null){
            text += "Comment:\n";
            text += comment;
            text += "\n\n";
        }

        tasks.setText(text);
        tasks.setCaretPosition(0);
    }

    private CheckBoxList checkBoxList;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane applications;
    private javax.swing.JScrollPane categories;
    private javax.swing.JList categoriesList;
    private javax.swing.JCheckBox checkAll;
    private javax.swing.JTextArea console;
    private javax.swing.JButton exit;
    private javax.swing.JButton generate;
    private javax.swing.JLabel generating;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea tasks;
    private javax.swing.JCheckBox uncheckAll;
    // End of variables declaration//GEN-END:variables

    public void generationProcessFinished(int resultCode) {
        provideFeedback.finish();
        generate.setEnabled(true);
        switch(resultCode){
            case GenerateScript.OK:
                SaveTo saveTo = new SaveTo(this, true);
                saveTo.setLocationRelativeTo(null);
                saveTo.setVisible(true);
                File scriptFile = saveTo.getFilePath();
                if(scriptFile != null){
                    int result = generateScript.saveScript(scriptFile);
                    savingProcessFinished(result, scriptFile);
                }else{
                    generating.setText("Script not saved!");
                    Thread th = new Thread(){
                        @Override
                        public void run(){
                            if (!generating.isVisible()) {
                                generating.setVisible(true);
                            }
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException ex) {
                                Log.getInstance().log(Log.ERROR, ex.getLocalizedMessage());
                            }
                            if(generating.getText().equalsIgnoreCase("Script not saved!")) generating.setVisible(false);
                        }
                    };
                    th.start();
                }
                break;
            case GenerateScript.ERROR:
                break;
        }
    }

    public void savingProcessFinished(int resultCode, File scriptFile) {
        provideFeedback.finish();
        switch(resultCode){
            case GenerateScript.OK:
                int response = JOptionPane.showConfirmDialog(this, "Script saved.\nDo you want to execute it now?", "Script saved", JOptionPane.YES_NO_OPTION);
                switch(response){
                    case JOptionPane.YES_OPTION:
                        this.setSize(this.getWidth(), 640);
                        this.update(this.getGraphics());
                        this.setLocationRelativeTo(null);
                        ejecuteScript = new ExecuteScript(scriptFile, console);
                        Thread th = new Thread(ejecuteScript);
                        th.start();
                        break;
                    case JOptionPane.NO_OPTION:
                        break;
                }
                break;
            case GenerateScript.ACCESS_DENIED:
                JOptionPane.showMessageDialog(this, "Error saving script. Acces denied", "Error", JOptionPane.ERROR_MESSAGE);
                break;
            case GenerateScript.ERROR:
                JOptionPane.showMessageDialog(this, "Error saving script.\nSee log for details (AfterUbuntu.log)", "Error", JOptionPane.ERROR_MESSAGE);
                break;
        }
    }

    private class ProvideFeedback implements Runnable{

        private boolean finish;

        public ProvideFeedback(){
            finish = false;
        }

        public void run() {
            while(!finish){
                try {
                    if (!generating.isVisible()) {
                        generating.setVisible(true);
                    }
                    Thread.sleep(500);
                    if(generating.getText().equalsIgnoreCase("Generating script.  ")){
                        generating.setText("Generating script.. ");
                        continue;
                    }
                    if(generating.getText().equalsIgnoreCase("Generating script.. ")){
                        generating.setText("Generating script...");
                        continue;
                    }
                    if(generating.getText().equalsIgnoreCase("Generating script...")){
                        generating.setText("Generating script.  ");
                        continue;
                    }
                    if(generating.getText().equalsIgnoreCase("Saving script.  ")){
                        generating.setText("Saving script.. ");
                        continue;
                    }
                    if(generating.getText().equalsIgnoreCase("Saving script.. ")){
                        generating.setText("Saving script...");
                        continue;
                    }
                    if(generating.getText().equalsIgnoreCase("Saving script...")){
                        generating.setText("Saving script.  ");
                        continue;
                    }
                } catch (InterruptedException ex) {
                    Log.getInstance().log(Log.ERROR, ex.getLocalizedMessage());
                }

            }
            generating.setVisible(false);
        }

        public void finish(){
            finish = true;
        }

    }

}
